package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.Service.DormitoryService;
import org.gdpu.Service.ExpenseService;
import org.gdpu.Service.PowerGroupService;
import org.gdpu.Service.StudentService;
import org.gdpu.base.PageView;
import org.gdpu.model.*;
import org.gdpu.util.ExcelUtil;
import org.gdpu.vo.DormitoryVO;
import org.gdpu.vo.ExpenseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-3-6
 * Time: 下午2:45
 * To change this template use File | Settings | File Templates.
 */
@Component("dormitory")
@Scope("prototype")
public class DormitoryAction extends MyActionSupport implements ModelDriven<DormitoryVO> {

    @Qualifier("excelUtil")
    @Autowired
    private ExcelUtil excelUtil;
    private DormitoryService dormitoryService;
    private PowerGroupService powerGroupService;
    private final DormitoryVO dormitoryVO = new DormitoryVO();
    private final static Logger logger = LogManager.getLogger(StudentAction.class);

    public String importDormitory() {
        try {
            if (dormitoryVO.getFileName().isEmpty()) {
                dormitoryVO.setResultMessage("<script>alert('请选择文件！');location.href='/page/dormitoryManagement/importDormitory.jsp';</script>");
                return ERROR;
            }
            List<Dormitory> dos = new ArrayList<Dormitory>();
            List<Object> obj = excelUtil.readExcelByPath(dormitoryVO.getFileName(),Dormitory.class, 1, 0);
            for (int i = 0; i < obj.size(); i++) {
                dos.add((Dormitory) obj.get(i));
            }
            String campus = dos.get(0).getCampus().getCampusName();
            int count = 0;
            int failCount = 0;
            StringBuffer sbr = new StringBuffer();
            for (Dormitory dormitory : dos) {
                if(dormitoryService.findById(dormitory.getDormitoryId(),campus) != null){
                    if(sbr.toString().equals(""))
                        sbr.append("<div style='color:RED'></br>失败记录，已存在的宿舍编号：</br>");
                    sbr.append(dormitory.getDormitoryId()+"   ");
                    ++failCount;
                    if(failCount%12 == 0)
                        sbr.append("</br>");
                }
                else{
                    dormitoryService.save(dormitory);
                    User user = new User();
                    Expense expense = new Expense();
                    String dormitoryId = dormitory.getDormitoryId().substring(0,1) + dormitory.getDormitoryId().substring(2,5);
                    if(campus.equals("大学城校区"))
                        user.setUserName("DXC" + dormitoryId);
                    else if(campus.equals("赤岗校区"))
                        user.setUserName("CG" + dormitoryId);
                    else
                        user.setUserName("ZS" + dormitoryId);
                    user.setPassword(dormitoryId);
                    user.setDormitory(dormitory);
                    user.setPowerGroup(powerGroupService.findByName("学生宿舍"));
                    dormitoryService.save(user);

                    expense.setDormitory(dormitory);
                    dormitoryService.save(expense);
                    ++count;
                }
            }
            dormitoryVO.setResultMessage("初始化"+campus + dos.get(0).getSex() +"宿舍信息，"+"共有"+obj.size()+"条记录，成功导入"+count+"条记录，"+"请查看数据库。</br>" +sbr);
            logger.trace("initialise the dormitory records success");
            return SUCCESS;
        } catch (RuntimeException e) {
            dormitoryVO.setResultMessage(e.getMessage());
            logger.error(e);
            return ERROR;
        }
    }

    @Resource(name = "powerGroupServiceImpl")
    public void setPowerGroupService(PowerGroupService powerGroupService) {
        this.powerGroupService = powerGroupService;
    }

    @Resource(name = "dormitoryServiceImpl")
    public void setDormitoryService(DormitoryService dormitoryService) {
        this.dormitoryService = dormitoryService;
    }

    @Override
    public DormitoryVO getModel() {
        return dormitoryVO;
    }
}
